package vno.fux.res.pool
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import vno.fux.res.manager.LoadState;
	import vno.fux.res.manager.ResourceManager;
	import vno.fux.utils.BitmapUtils;
	

	public class PlayerResource extends Resource
	{
		use namespace RM_CRM;
		RM_CRM var _walk:AutoBitmap;
		private var _walkAnimeMatrix:AutoAnimeMatrix;
		public function PlayerResource(id_:uint, setting:XML)
		{
			super(id_);
		}
		
		override public function create():void
		{
			this._loadStateDic = new Dictionary(true);
			initDataMatrix();
		}
		private function initDataMatrix():void
		{
			_walkAnimeMatrix = new AutoAnimeMatrix;
			_walk = new AutoBitmap;
			var tempBitmap:BitmapAttacher = new BitmapAttacher;
			tempBitmap.addEventListener(ResourceAttacher.RECIEVE, doAnime);
			_walk.attach(tempBitmap);
			this._loadStateDic[_walkAnimeMatrix] = LoadState.NOT_LOAD;
		}
		
		override public function destroy():void
		{
			destroyMatrix();
			_walk = null;
			this._loadStateDic = null;
		}
		
		private function destroyMatrix():void
		{
			_walkAnimeMatrix.detachAll();
			for each(var bitmapDataVector:Vector.<BitmapData> in _walkAnimeMatrix.matrix)
			{
				for each(var bitmapData:BitmapData in bitmapDataVector)
				{
					bitmapData.dispose();
				}
			}
			_walkAnimeMatrix = null;
		}
		
		public function get walkAnimeMatrix():AutoAnimeMatrix
		{
			if(_loadStateDic[_walkAnimeMatrix] == LoadState.NOT_LOAD)
			{
				_loadStateDic[_walkAnimeMatrix] = LoadState.PRE_LOAD;
				ResourceManager.getInstance().cha.load(id);
			}
			return _walkAnimeMatrix;
		}
		
		override public function setLoadState(state:LoadState):void
		{
			if(state.target == _walk)
			{
				_loadStateDic[_walkAnimeMatrix] = state.state;
				return;
			}
			super.setLoadState(state);
		}
		
		private function doAnime(event:Event):void
		{
			event.target.removeEventListener(BitmapAttacher.RECIEVE, doAnime);
			_walk.detachAll();
			_walk = null;
			_walkAnimeMatrix.matrix = BitmapUtils.divide((event.target as BitmapAttacher).bitmapData, 8, 8);
		}
	}
}